#!/usr/bin/perl

use strict;
use DBI;
use Time::localtime;
use XML::Simple;

my $CONFIG = XMLin($ENV{'HACKABOT_CFG'});
my $DBCFG = $CONFIG->{'cmdconfig'}->{'database'};

my $dbhost = $DBCFG->{'host'};
my $dbname = $DBCFG->{'name'};
my $dbuser = $DBCFG->{'user'};
my $dbpass = $DBCFG->{'pass'};

sub add_score {
	my $name = shift;
	my $val = shift;
	my $nick = shift;
	my $chan = shift;
	my ($dbh, $sth);

	$dbh = DBI->connect("DBI:mysql:$dbname:$dbhost", $dbuser, $dbpass, { PrintError => 0 });
	if (!$dbh) {
		die "see: Failed to connect to database\n";
	}
	
	my $time = `date "+%F %R"`;
	chomp $time;

	$nick = $dbh->quote($nick);
	$chan = $dbh->quote($chan);
	$time = $dbh->quote($time);
	$name = $dbh->quote($name);

	$dbh->do("INSERT score SET date = $time, name = $name, value = (value + $val), chan = $chan, nick = $nick") or
	$dbh->do("UPDATE score SET date = $time, value = (value + $val), chan = $chan, nick = $nick WHERE name = $name") or
	die "see: DB stuff failed.\n";
	
	$sth = $dbh->prepare("SELECT value FROM score WHERE name = $name");
	$sth->execute;
	my $row = $sth->fetchrow_hashref;
	my $value = $row->{'value'};
	$sth->finish();

	$dbh->disconnect;

	return $value;
}

my ($nick, $chan, $name, $value);
my $verbose = 0;
while (<>) {
	if (/^nick\s+(\S*)/) {
		$nick = $1;
	}
	elsif (/^to\s+(\S*)/) { # We assume there is only one name listed
		$chan = $1;
	}
	elsif (/^msg\s+!.*/) {
		exit; # I don't care about seeing !commands
	}
	elsif (/^msg.*\s+(\S+)\+\+\s+/) {
		$name = $1;
		$value = 1;
		if (/\s-v\s/ or /\s--verbose\s/) {
			$verbose = 1;
		}
	}
	elsif (/^msg.*\s+(\S+)--\s+/) {
		$name = $1;
		$value = -1;
		if (/\s-v\s/ or /\s--verbose\s/) {
			$verbose = 1;
		}
	}
}

if (defined $name and defined $nick and defined $chan) {
	if (lc($name) eq lc($nick)) {
		if ($value > 0) {
			print "send $nick: No self promotion!\n";
			$value = -5;
		}
		elsif ($value < 0) {
			print "send $nick: Aww, cheer up, you can keep your point.\n";
			$value = 0;
		}
		
	}
	
	my $newval = add_score($name, $value, $nick, $chan);
	if ($verbose) {
		if ($newval == "1") {
			print "send $name has scored $newval point!\n";
		}
		else {
			print "send $name has scored $newval points!\n";
		}
	}
}
